package com.fjec.paid.rabbitmq.consumer;

import com.fjec.paid.service.YsPayDelayQueryService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@Component
@Slf4j
public class YsPayDelayQueryConsumer {
    @Resource
    private YsPayDelayQueryService ysPayDelayQueryService;

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(
                            value = "${fjec.paid.yspaydelayquery.queue.name}",
                            durable = "${fjec.paid.yspaydelayquery.queue.durable}"
                    ),
                    exchange = @Exchange(
                            value = "${fjec.paid.yspaydelayquery.exchange.name}",
                            durable = "${fjec.paid.yspaydelayquery.exchange.durable}",
                            type = "${fjec.paid.yspaydelayquery.exchange.type}",
                            ignoreDeclarationExceptions = "${fjec.paid.yspaydelayquery.exchange.ignoreDeclarationExceptions}"
                    ),
                    key = "${fjec.paid.yspaydelayquery.router.key}"
            )
    )
    @RabbitHandler
    public void onYsPayDelayQuery(Message message, Channel channel, @Headers Map<String, Object> headers) throws Exception {
        Long deliveryTag = MapUtils.getLong(headers, AmqpHeaders.DELIVERY_TAG);
        try {
            String orderId = new String(message.getBody(), StandardCharsets.UTF_8);
            ysPayDelayQueryService.handle(orderId);
            channel.basicAck(deliveryTag, true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            channel.basicReject(deliveryTag, false);
        }

    }
}
